import subprocess
from nicegui import ui
from niceguiToolkit.layout import inject_layout_tool
from datetime import datetime
# inject_layout_tool()

ui.add_head_html(
    """
<style>.my-full-h-area .q-field__control{height:100%}</style>
"""
)


def evaluate_code(student_code, correct_code):
    try:
        # 将学生代码写入文件
        with open("student_code.py", "w") as file:
            file.write(student_code)

        # 尝试运行学生代码
        result = subprocess.run(["python", "student_code.py"], capture_output=True, text=True)

        # 检查是否有编译错误
        if result.returncode != 0:
            return False, f"编译错误：\n{result.stderr}"

        student_output = result.stdout.strip()  # 学生代码的输出

        # 执行正确的代码
        result = subprocess.run(["python", "-c", correct_code], capture_output=True, text=True)
        correct_output = result.stdout.strip()  # 正确代码的输出

        # 比较学生输出和正确输出
        if student_output == correct_output:
            return True, "答案正确！"
        else:
            return False, "答案不正确。"
    except Exception as e:
        return False, f"运行时错误：{e}"

    # 示例使用方法


intput = ""


def change(e):
    global intput
    intput = e.value
    label.set_text(intput)


def ondick():
    if_true, text = evaluate_code(intput, "print(2)")
    print(intput)
    ui.notify(text)
    print(text)
    print("111111111111")


def get_topic(id):
    return ['小明想学会算术,请你帮帮他', '给出1+1的结果!', '注:本题无输入']


with ui.card().style('width:800px;height:500px'):
    title = ui.label()
    ui.timer(1.0, lambda: {label.set_text(f'{datetime.now():%X}'),print(datetime.now())})

    with ui.splitter().classes('w-full h-full') as spitter:
        with spitter.before:
            with ui.scroll_area().classes('w-32 h-32 border').style('width:100%;height:100%'):
                ui.label(get_topic(0)[0])
                ui.separator()
                ui.label(get_topic(0)[1])
                ui.separator()
                ui.label(get_topic(0)[2])
        with spitter.after:
            ui.textarea('输入代码', value=intput, on_change=lambda e: change(e)).props('outlined').classes(
                'my-full-h-area w-full h-full')
            ui.button('提交', on_click=ondick)






label = ui.label("")
ui.run()
# ui.run(uvicorn_reload_excludes="student_code.py")
